package com.Controls;

import com.HMI.Main;
import com.Resources.LookUpORP;

public class ORP2Cl implements Runnable {

	private boolean Control = false; // Activity of the controller (on/off)
	private boolean Delay = false; // Delay between control loops
	private final double lowThresh = 1.5; // Lower bound on Cl ppm
	private final double hiThresh = 2.0; // Higher bound on Cl ppm
	//private final double dblPrec = 0.9; // Determine when to take off delay
	//private double dblPpmB4 = 0; // ppm prior to chemical injection
	private double dblPpmExp = 0; // expected ppm injection
	private int intDelay = 0;
	
	private int dum = 0;
	private int dum2 = 0;

	//private ClControl Controller;

	private Main parent;
	
	public ORP2Cl(Main parent) {
		this.parent = parent;
	}
	
	@Override
	public void run() {
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {  }
		
		while (true) {
			try {
				ClSensor();
			} catch (InterruptedException e) {	
		        System.out.println("Cl failed");
			}
			
			try {
				Thread.sleep(20000);
			} catch (InterruptedException e) {  }
		}
	}

	public void ClSensor() throws InterruptedException {
		// Functions for reading sensor and converting it to Cl ppm
		//double dblORP = parent.getOrpValue();
		//double dblPH = parent.getPhValue();
		
		double dblORP = 700;
		double dblPH = 7.7;
		double dblPPM;
		int index = ((int) (dblPH/0.02)) - 326;		// 6.52 being lowest pH value based on lookup table
		if (index < 0)
			index = 0;
		else if (index > 99)
			index = 99;
		
		dblPPM = LookUpORP.a[index]*Math.exp(dblORP*LookUpORP.b[index]);
		//System.out.println("ORP: " + dblORP);
		//Controls test
		/*dum2++;
		dum2 = dum2%80;
		if (dum2<20)
			dum=0;
		else if (dum2<40)
			dum=1;
		else if (dum2<60)
			dum=2;
		else
			dum=3;
		
		if (dum==0)
			dblPPM = 2.5;
		else if (dum==1)
			dblPPM = 1.7;
		else if (dum==2)
			dblPPM = 1.3;
		else if (dum==3)
			dblPPM = 1.49;*/
		//End Controls test
		//System.out.println("dum2: " + dum2);
		dblPPM = 1.3;
		//System.out.println("PPM: " + dblPPM);

		outHMI(dblPPM); // Output sensor readings to HMI

		// Determine when to activate controller
		if (dblPPM < lowThresh) {
			Control = true;
		} else if (dblPPM > hiThresh) {
			Control = false;
		}

		/*
		// Determine when to take off delay
		if ((dblPPM - dblPpmB4) > (dblPrec * dblPpmExp)) {
			Delay = false;
		}

		if (Control && !Delay) {
			dblPpmB4 = dblPPM;
			System.out.println("B4 Control Call" + dblPPM);
			dblPpmExp = ClControl.Control(dblPPM);
			Delay = true;
		}*/
		
		/*if (Delay)
			intDelay++;
		
		if (intDelay > 9) {
			intDelay = 0;
			Delay = false;
		}*/
		
		if (Control) {
			//System.out.println("B4 Control Call" + dblPPM);
			dblPpmExp = ClControl.Control(dblPPM);
			//Delay = true;
		}
	}

	private void outHMI(double dblPpm) {
		// Pass Cl ppm value to HMI for graphing stuff
	}
}
